package com.wyj.utils

import android.app.Activity
import android.app.Application
import android.webkit.WebView
import com.hjq.toast.Toaster
import com.qmuiteam.qmui.arch.QMUISwipeBackActivityManager
import com.tencent.mmkv.MMKV
import com.wyj.log.LogUtil
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import me.jessyan.autosize.utils.ScreenUtils

object MApplication {
    @JvmStatic
    lateinit var application: Application
        private set

    @JvmStatic
    fun onCreate(app: Application, isMainProcess: Boolean) {
        application = app
        MMKV.initialize(app)
        //屏幕适配监听器
        val autoSIzeInstance = AutoSizeConfig.getInstance()
        autoSIzeInstance.setUseDeviceSize(true).setBaseOnWidth(true).onAdaptListener = object : onAdaptListener {
            override fun onAdaptBefore(target: Any, activity: Activity) {
                //使用以下代码, 可支持 Android 的分屏或缩放模式, 但前提是在分屏或缩放模式下当用户改变您 App 的窗口大小时
                //系统会重绘当前的页面, 经测试在某些机型, 某些情况下系统不会重绘当前页面, ScreenUtils.getScreenSize(activity) 的参数一定要不要传 Application!
                val (width, height) = ScreenUtils.getScreenSize(activity)
                autoSIzeInstance.screenWidth = width
                autoSIzeInstance.screenHeight = height
                if (width < height) {
                    autoSIzeInstance.designWidthInDp = 360
                    autoSIzeInstance.designHeightInDp = 640
                } else {
                    autoSIzeInstance.designWidthInDp = 640
                    autoSIzeInstance.designHeightInDp = 360
                }
            }

            override fun onAdaptAfter(target: Any, activity: Activity) {
            }
        }
        arrayListOf("com.hjq.logcat.LogcatActivity").forEach {
            try {
                Class.forName(it).let {
                    autoSIzeInstance.externalAdaptManager.addCancelAdaptOfActivity(it)
                }
            } catch (e: Exception) {
            }
        }
        Toaster.init(app)
        LogUtil.init(app)
        QMUISwipeBackActivityManager.init(app)
        //fix bug at  努比亚NX563J
        //Using WebView from more than one process at once with the same data directory is not supported
        if (SdkVersionUtils.isAndroid9 && !isMainProcess) {
            WebView.setDataDirectorySuffix(QbSdkHelper.getCurrentProcessName(app))
        }
    }
}